package com.jumi.microservice.controller.api;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.jm.member.common.core.utils.ServletUtils;
import com.jm.member.common.jwt.constant.JwtAdminInfo;
import com.jumi.microservice.common.base.AjaxResult;
import com.jumi.microservice.common.base.dto.ResponseResult;
import com.jumi.microservice.dto.reponse.api.RealnameWithdraw;
import com.jumi.microservice.dto.request.RealNameUpdateRequest;
import com.jumi.microservice.entity.JmGoldPromoterReview;
import com.jumi.microservice.entity.JmIdentityAuthentication;
import com.jumi.microservice.entity.JmRealnameAuthentication;
import com.jumi.microservice.entity.JmUser;
import com.jumi.microservice.enums.CheckStatus;
import com.jumi.microservice.enums.BankType;
import com.jumi.microservice.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.http.impl.client.CloseableHttpClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.*;

import static cn.hutool.core.util.ObjectUtil.isEmpty;
import static cn.hutool.core.util.ObjectUtil.isNotEmpty;

/**
 * <p>
 * 用户实名认证表 前端控制器
 * </p>
 *
 * @author 要挑客户管理团队
 * @since 2020-08-03
 */
@RestController
@RequestMapping("/api/realname")
@Api(value = "C-用户实名认证申请", tags = {"C-用户实名认证申请接口"})
public class JmRealnameController {

    @Autowired
    IJmRealnameAuthenticationService realNameService;

    @Autowired
    IJmUserService userService;
    private static CloseableHttpClient httpClient;
    @Autowired
    IJmGoldPromoterReviewService goldService;

    @DubboReference(check = false)
    IWalletInOrOutService iWalletInOrOutService;

    @Autowired
    IJmIdentityAuthenticationService identityAuthenticationService;

    @PostMapping("/save")
    @ApiOperation("实名认证添加")
    public ResponseResult save(@Validated RealNameUpdateRequest request) {
        Integer uid = ServletUtils.getIntHeader(JwtAdminInfo.apiUserId);
        JmUser byId = userService.checkUserExist(uid);

        /**
         * 如果没有当前登录人信息，返回错误。
         */

        if (isNotEmpty(byId)) {

            //检验身份证是否重复
            QueryWrapper check = new QueryWrapper();
            check.eq("idcard", request.getIdcard());
            JmRealnameAuthentication checkIdCard = realNameService.getOne(check);
            if (isNotEmpty(checkIdCard) && !uid.equals(checkIdCard.getUid()))return ResponseResult.error("此身份证已被注册!");

            QueryWrapper wrapper = new QueryWrapper();
            wrapper.eq("uid", uid);
            JmRealnameAuthentication realName = realNameService.getOne(wrapper);
            /**
             * 如果为空，添加--
             * 如果不为空，并且处于待审核状态允许更新
             */
            LocalDateTime now = LocalDateTime.now();
            if (isNotEmpty(realName) && !realName.getStatus().equals(CheckStatus.已通过)) {
                realName.setUpdateTime(now);
                realName.setStatus(CheckStatus.待审核);
                realName.setRemark("");
                realName.setCreateTime(now);
                realName.setUpdateTime(now);
                BeanUtils.copyProperties(request, realName);
                realNameService.updateById(realName);
            } else {
                realName = new JmRealnameAuthentication();
                BeanUtils.copyProperties(request, realName);
                realName.setCreateTime(now);
                realName.setUid(uid);
                realName.setName(byId.getName());
                realName.setAdminId(uid.longValue());
                realName.setAdminName(byId.getName());
                realName.setUpdateTime(now);
                realName.setStatus(CheckStatus.待审核);
                byId.setTruename(request.getTruename());
                userService.updateById(byId);
                realNameService.save(realName);
            }
            return ResponseResult.success();
        }
        return ResponseResult.error("未查询到用户信息!");

    }

    @PostMapping("/getWithdraw")
    @ApiOperation("获取提现金额和提现方式")
    public ResponseResult getWithdraw() {
        Integer uid = ServletUtils.getIntHeader(JwtAdminInfo.apiUserId);
        JmUser byId = userService.checkUserExist(uid);

        RealnameWithdraw data = new RealnameWithdraw();

//        data.setAvailablePredeposit(byId.getAvailablePredeposit());
        //改为调用钱包服务获取可提现金额
        data.setAvailablePredeposit(iWalletInOrOutService.waitCash(uid.longValue()));

        ResponseResult checkReturn = this.checkRealIdte(uid);

        if (checkReturn.getCode() == 500) {
                return checkReturn;
        }

        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("uid", uid);
        JmRealnameAuthentication realName = realNameService.getOne(wrapper);

        data.setIdCard(realName.getIdcard());
        data.setAliCode(realName.getAliCode());
        data.setBankCard(realName.getBankCard());
        data.setTruename(realName.getTruename());
        data.setTypeImg("11212121");
        data.setPhone(realName.getBankPhone());
        data.setBankType(realName.getBankType());

        return ResponseResult.success(data);
    }

    @PostMapping("/updateBank")
    @ApiOperation("解绑银行卡号")
    public ResponseResult updateBank() {
        Integer uid = ServletUtils.getIntHeader(JwtAdminInfo.apiUserId);
        JmUser byId = userService.checkUserExist(uid);

        UpdateWrapper<JmRealnameAuthentication> updateWrapper = new UpdateWrapper<JmRealnameAuthentication>();
        updateWrapper.set("bank_card", null);
        updateWrapper.set("bank_type", null);
        updateWrapper.eq("uid", uid);

        return ResponseResult.success(realNameService.update(updateWrapper));

    }

    @PostMapping("/bindAliOrBank")
    @ApiOperation("绑定支付宝或者银行卡")
    public ResponseResult bindAliOrBank(String aliCode, String bankCode, String bankPhone) {
        Integer uid = ServletUtils.getIntHeader(JwtAdminInfo.apiUserId);
        JmUser byId = userService.checkUserExist(uid);

        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("uid", uid);
        JmRealnameAuthentication realName = realNameService.getOne(wrapper);

        if (isEmpty(realName)) {
            return ResponseResult.error("还未实名认证!");
        }

//        if (!StrUtil.equals(trueName, realName.getTruename())) {
//            return ResponseResult.error("真实姓名与实名认证姓名不符!");
//        }

        if (isNotEmpty(bankCode)) {

            String url = "https://ccdcapi.alipay.com/validateAndCacheCardInfo.json?_input_charset=utf-8&cardNo="+bankCode+"&cardBinCheck=true";

            String result2= HttpUtil.get(url, CharsetUtil.CHARSET_UTF_8);

            JSONObject jsonObject = JSONUtil.parseObj(result2);

            if (jsonObject.getBool("validated") == true) {

                String type = jsonObject.getStr("bank");
                realName.setBankType(BankType.getTypeByValue(type));

            } else {
                realName.setBankType("银行卡");
            }

        } else {
            realName.setBankType("银行卡");
        }

        LocalDateTime now = LocalDateTime.now();
        realName.setUpdateTime(now);
        realName.setAliCode(aliCode);
        realName.setBankCard(bankCode);
        realName.setBankPhone(bankPhone);

        Map<String,Object> map = new HashMap<>();

        map.put("bool",realNameService.updateById(realName));
        map.put("bankName",realName.getBankType());

        return ResponseResult.success(map);

    }

    @PostMapping("/goldGetWithdraw")
    @ApiOperation("金牌获取提现金额和提现方式")
    public ResponseResult goldGetWithdraw() {
        Integer uid = ServletUtils.getIntHeader(JwtAdminInfo.apiUserId);
        JmUser byId = userService.checkUserExist(uid);

        RealnameWithdraw data = new RealnameWithdraw();

//        data.setAvailablePredeposit(byId.getAvailablePredeposit());
        //改为调用钱包服务获取可提现金额
        data.setAvailablePredeposit(iWalletInOrOutService.waitCash(uid.longValue()));

        ResponseResult checkReturn = this.checkRealIdte(uid);

        if (checkReturn.getCode() == 500) {
            return checkReturn;
        }

        QueryWrapper wrapper1 = new QueryWrapper();
        wrapper1.eq("member_id", uid);
        JmGoldPromoterReview goldList = goldService.getOne(wrapper1);

        if (!isEmpty(goldList)) {
            if (goldList.getStatus().getValue() == 0) {
                return ResponseResult.error(500,"金牌推广商申请未审核,请等待提交通过后再次申请提现!", 6);
            }
            if (goldList.getStatus().getValue() == 2) {
                return ResponseResult.error(500,"金牌推广商拒绝,请重新提交通过后再次申请提现!", 7);
            }

            QueryWrapper wrapper = new QueryWrapper();
            wrapper.eq("uid", uid);
            JmRealnameAuthentication realName = realNameService.getOne(wrapper);

            data.setAliCode(goldList.getAliCode());
            data.setBankCard(realName.getBankCard());
            data.setTruename(goldList.getAliName());
            data.setBankType(realName.getBankType());

            Map map = new HashMap();
            map.put("realData", data);
            map.put("goldData", goldList);
            return ResponseResult.success(map);
        } else {
            return ResponseResult.error("还未申请金牌推广商!");
        }

    }

    @PostMapping("/getRealName")
    @ApiOperation("获取实名认证信息")
    public ResponseResult getRealName () {
        Integer uid = ServletUtils.getIntHeader(JwtAdminInfo.apiUserId);
        JmUser byId = userService.checkUserExist(uid);

        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("uid", uid);
        JmRealnameAuthentication realName = realNameService.getOne(wrapper);

        if (isEmpty(realName)) {
            return ResponseResult.error(500,"还未实名认证!", 0);
        }

        return ResponseResult.success(realName);

    }

    public ResponseResult checkRealIdte(Integer uid) {

        //实名验证
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("uid", uid);
        JmRealnameAuthentication realName = realNameService.getOne(wrapper);

        if (isEmpty(realName)) {
            return ResponseResult.error(500,"还未实名认证!", 0);
        }

        if (realName.getStatus().getValue() == 0) {
            return ResponseResult.error(500,"实名申请未审核,请等待提交通过后再次申请提现!", 1);
        }
        if (realName.getStatus().getValue() == 2) {
            return ResponseResult.error(500,"实名申请拒绝,请重新提交通过后再次申请提现!", 2);
        }

        //店长角色认证
        QueryWrapper idwrapper = new QueryWrapper();
        idwrapper.eq("uid", uid);
        JmIdentityAuthentication identity = identityAuthenticationService.getOne(idwrapper);

        if (isEmpty(identity)) {
            return ResponseResult.error(500,"未店长入驻或店长认证!", 3);
        }

        if (identity.getStatus().getValue() == 0) {
            return ResponseResult.error(500,"店长认证或入驻申请未审核,请等待提交通过后再次申请提现!", 4);
        }
        if (identity.getStatus().getValue() == 2) {
            return ResponseResult.error(500,"店长认证或入驻申请拒绝,请重新提交通过后再次申请提现!", 5);
        }

        return ResponseResult.success();

    }

}
